import WidgetKit
import SwiftUI
import YJYWidgetUIModule

struct Provider: TimelineProvider {
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), userName: "xxx", quote: "xxx", imageUrl: URL(string: "https://betasystem.gsf.netease.com/first_banner.png"))
    }

    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), userName: "xxx", quote: "xxx", imageUrl: URL(string: "https://betasystem.gsf.netease.com/first_banner.png"))
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        // 从 UserDefaults 加载保存的文本
        // 从 UserDefaults 加载保存的文本
        let userDefaults = UserDefaults(suiteName: "group.com.netease.ma68")
        let savedText = userDefaults?.string(forKey: "SavedText") ?? "无数据"
        // 从 UserDefaults 加载保存的文本
        // Fetch data from network
        NetworkService.shared.fetchQuote { result in
            DispatchQueue.main.async {
                var entries: [SimpleEntry] = []
                
                switch result {
                case .success(let quoteString):
                    let userName = savedText
                    let imageUrl = URL(string: "https://betasystem.gsf.netease.com/first_banner.png")
                    let entry = SimpleEntry(date: Date(), userName: userName, quote: quoteString, imageUrl: imageUrl)
                    entries.append(entry)
                case .failure(_):
                    let userName = "\(savedText) - No quote available"
                    let entry = SimpleEntry(date: Date(), userName: userName, quote: "xxx", imageUrl: URL(string: "https://betasystem.gsf.netease.com/first_banner.png"))
                    entries.append(entry)
                }
                
                let timeline = Timeline(entries: entries, policy: .atEnd)
                completion(timeline)
            }
        }
        //        let userDefaults = UserDefaults(suiteName: "group.com.netease.ma68")
        //        let savedText = userDefaults?.string(forKey: "SavedText") ?? "无数据"
        //        let entry = SimpleEntry(date: Date(), userName: savedText)
        //        print("UserName: \(entry.userName)") // 添加这一行
        //        let timeline = Timeline(entries: [entry], policy: .atEnd)
        //        //    let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(15 * NSEC_PER_SEC))) // 15秒后更新
        //
        //        completion(timeline)
    }
}

struct SimpleEntry: TimelineEntry {
    let date: Date
    var userName: String
    var quote: String
    var imageUrl: URL?

}

struct WidgetEntryView : View {
    var entry: Provider.Entry
    @State private var count: Int = 0
    //针对不同尺寸的 Widget 设置不同的 View
    @Environment(\.widgetFamily) var family: WidgetFamily // 尺寸环境变量

    var body: some View {
        MidView(userName: entry.userName, quote: entry.quote)
//        VStack(alignment: .leading) {
//            if let imageUrl = entry.imageUrl {
//                AsyncImage(url: imageUrl) { image in
//                    image.resizable()
//                        .frame(width: 100, height: 100) // 调整大小以适应你的需求
//                } placeholder: {
//                    Image(systemName: "photo")
//                        .resizable()
//                        .frame(width: 100, height: 100)
//                }
//            }
//            
//            
//            Text(entry.userName)
//                .font(.headline)
//                .padding(.top, 8)
//            
//            Spacer()
//        }
//        .padding()
    }
}

struct MyWidget: Widget {
    let kind: String = "MyWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            WidgetEntryView(entry: entry)
        }
        
        .contentMarginsDisabled()
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
        .supportedFamilies([.systemSmall,.systemMedium,.systemLarge])
    }
}

struct MyWidget_Previews: PreviewProvider {
    static var previews: some View {
        WidgetEntryView(entry: SimpleEntry(date: Date(), userName: "", quote: "xxx"))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}
